package com.vanke.kotlin_mvp.addedit

import android.app.Activity
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.vanke.kotlin_mvp.R
import kotlinx.android.synthetic.main.addedit_fragment.*

/**
 * @name Kotlin_MVP
 * @package name：com.vanke.kotlin_mvp.addedit
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/8/22 16:51
 */
class AddEditTaskFragment : Fragment(), AddEditTaskContract.View {

    override var presenter: AddEditTaskContract.Presenter? = null

    override var isActive: Boolean = false
        get() = isAdded

    override fun onResume() {
        super.onResume()
        presenter?.start()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        with(activity.findViewById<FloatingActionButton>(R.id.fad_edit_task_done)) {
            setImageResource(R.drawable.ic_done)
            setOnClickListener {
                presenter?.saveTask(taskTitle.text.toString(), taskDescription.text.toString())
            }
        }
        super.onActivityCreated(savedInstanceState)
    }

    private lateinit var taskTitle: TextView
    private lateinit var taskDescription: TextView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.addedit_fragment, container, false)
        with(root) {
            taskTitle = findViewById<TextView>(R.id.add_task_title)
            taskDescription = findViewById<TextView>(R.id.add_task_description)
        }
        setHasOptionsMenu(true)
        return root
    }

    override fun showEmptyTaskError() {
        Snackbar.make(add_task_title, "To-Do cannot be empty", Snackbar.LENGTH_LONG).show()
    }

    override fun showTasksList() {
        with(activity) {
            setResult(Activity.RESULT_OK)
            finish()
        }
    }

    override fun setTitle(title: String) {
        taskTitle.text = title
    }

    override fun setDescription(description: String) {
        taskDescription.text = description
    }

    companion object {
        val ARGUMENT_EDIT_TASK_ID = "EDIT_TASK_ID"
        fun newInstance(): AddEditTaskFragment {
            return AddEditTaskFragment()
        }
    }
}